import Trucks.IsuzuElf
import Trucks.KamazCompass
import Trucks.MercedesBenzAtego
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlin.random.Random

class TruckGenerator {
    val channel: Channel<AbstractTruck> = Channel<AbstractTruck>()
    val scope: CoroutineScope = CoroutineScope(Job() + Dispatchers.Default)
    fun generate(interval: Int) {
        scope.launch {
            while (scope.isActive) {
                val truck: AbstractTruck = ListOfTrucks().getRandom()
                var product: AbstractProduct = ListOfProducts().getRandom()
                truck.products.add(product)
                var currentWeight: Double = product.weight
                while (currentWeight < truck.weightCapacity) {
                    product = ListOfProducts().getRandom(product.productCategory)
                    if (truck.products.any { it == product }) {
                        val index: Int = truck.products.indexOf(product)
                        truck.products[index].amount++
                    } else {
                        truck.products.add(product)
                    }
                    currentWeight += product.weight
                }
                channel.send(truck)
                delay((interval * 1000).toLong())
            }
        }
    }
}